<?php
declare (strict_types = 1);

namespace app\common\service;

use think\facade\Request;
use app\common\model\AdminDepartment as M;
use app\common\validate\AdminDepartment as V;

class AdminDepartment
{
    // 添加
    public static function goAdd($data)
    {
        //验证
        $validate = new V;
        if(!$validate->scene('add')->check($data))
        return ['msg'=>$validate->getError(),'code'=>201];
        try {
            M::create($data);
        }catch (\Exception $e){
            return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
        }
    }
    
    // 编辑
    public static function goEdit($data,$id)
    {
        $data['dept_id'] = $id;
        //验证
        $validate = new V;
        if(!$validate->scene('edit')->check($data))
        return ['msg'=>$validate->getError(),'code'=>201];
        try {
             M::where('dept_id', $id)->update($data);
        }catch (\Exception $e){
            return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
        }
    }

    // 删除
    public static function goRemove($id)
    {
        $model = M::where('dept_id', $id)->find();
        if ($model->isEmpty()) return ['msg'=>'数据不存在','code'=>201];

        $hasChild = M::where('parent_id', $id)->find();
        if (!empty($hasChild)) {
            return ['msg'=>'该部门下有子部门不可以删除','code' => 202];
        }

        $hasStaff = \app\common\model\AdminAdmin::where('dept_id', $id)->find();
        if (!empty($hasStaff)) {
            return ['msg'=>'该部门下有员工不可以删除','code' => 203];
        }

        try{
           M::where('dept_id', $id)->delete();
        }catch (\Exception $e){
            return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
        }
    }
}
